package com.example.campus.api_controller.shiro;

import com.example.campus.dao.model.shiro.Permission;
import com.example.campus.dao.model.shiro.Role;
import com.example.campus.dao.model.shiro.User;
import com.example.campus.dao.table_gateway.shiro.UserMapper;
import com.example.campus.page_controller.dto.ResponseResult;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.Set;

import static com.example.campus.common.BusinessConstants.ADMIN_API_BASE;


@RestController
@RequestMapping(ADMIN_API_BASE + "/users")
public class UserController {
    @Autowired
    UserMapper userMapper;

    @PostMapping
    public ResponseResult<String> addUser(@RequestBody User user) {
        userMapper.addUser(user);

        return ResponseResult.ok();
    }

    @GetMapping
    public ResponseResult<Set<User>> getAllUsers() {
        var users = userMapper.getAllUsers();
        return ResponseResult.ok(users);
    }

    @GetMapping("{id}")
    public  ResponseResult<User> getUserById(@PathVariable("id")long id){
        var user = userMapper.getUserById(id);
        return ResponseResult.ok(user);
    }

    @PutMapping
    public ResponseResult<String> updateRoleById(@Valid @RequestBody User user) {
        userMapper.updateRoleById(user);

        return ResponseResult.ok();
    }

    @DeleteMapping("{id}")
    public ResponseResult<String> deleteRoleById(@PathVariable("id")long id){
        userMapper.deleteUserById(id);
        return ResponseResult.ok();
    }

    @GetMapping("/{id}/roles")
    public  ResponseResult<Set<Role>> getRolesOfUserByUserId(@PathVariable("id")long id){
        var user = userMapper.getUserWithRoles(id);
        return ResponseResult.ok(user.getRoles());
    }

    @GetMapping("/{id}/perms")
    public  ResponseResult<Set<Permission>> getPermissionsOfUserByUserId(@PathVariable("id")long id){
        var user = userMapper.getUserWithRolesAndPermissions(id);
        var perms = new HashSet<Permission>();
        user.getRoles().forEach((r)->{
            perms.addAll(r.getPermissions());
        });
        return ResponseResult.ok(perms);
    }
}
